package com.github.icloudpay.pay.core.service.pay.alipay.service;

import java.math.BigDecimal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.github.icloudpay.pay.core.biz.PayChannelConfigBiz;
import com.github.icloudpay.pay.core.entity.PayChannelConfig;
import com.github.icloudpay.pay.core.inter.QueryPayStatusService;
import com.github.wxiaoqi.security.common.admin.pay.request.QueryPayStatusRequest;
import com.github.wxiaoqi.security.common.admin.pay.response.QueryPayStatusResponse;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import net.sf.json.JSONObject;


/**
 * 支付宝订单状态查询
 * @author hexufeng
 *
 */
@Service("aliQueryPayStatusService")
public class AliQueryPayStatusService implements QueryPayStatusService {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(AliQueryPayStatusService.class);

	@Autowired
	private PayChannelConfigBiz payChannelConfigBiz;

	@Override
	public QueryPayStatusResponse queryPayStatus(QueryPayStatusRequest request) {
		
		logger.info("****************调用支付宝订单状态查询接口开始*******************");

		QueryPayStatusResponse queryPayStatusResponse = new QueryPayStatusResponse();

		PayChannelConfig payChannelConfig = new PayChannelConfig();
		payChannelConfig.setMerId(request.getMerId());
		payChannelConfig.setPlatformId(request.getPlatformId());
		payChannelConfig.setPayChannelNo(request.getPayChannelNo());
		payChannelConfig.setPayCompanyNo(request.getPayCompanyNo());
		PayChannelConfig channelConfig = payChannelConfigBiz.getPayChannelConfig(payChannelConfig);
		if(null == channelConfig){
			queryPayStatusResponse.setSucess(false);
			queryPayStatusResponse.setCode(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getCode());
			queryPayStatusResponse.setMsg(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getMessage());
			return queryPayStatusResponse;
		}

		JSONObject json = new JSONObject();
		json.put("out_trade_no", request.getOrderId());
		String jsonStr = json.toString();
		logger.info("调用支付宝请求参数。。。。。。。{}", jsonStr);

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",channelConfig.getOutMerNo(),channelConfig.getOutMerKey(),"json","UTF-8",channelConfig.getOutMerPublicKey(),"RSA2");
		AlipayTradeQueryRequest tradeQueryRequest = new AlipayTradeQueryRequest();
		tradeQueryRequest.setBizContent(jsonStr);
		AlipayTradeQueryResponse response;
		try {
			response = alipayClient.execute(tradeQueryRequest);
			logger.info("调用支付宝响应参数。。。。。。。{}", EntityUtils.beanToMap(response));
			if(response.isSuccess() && "10000".equals(response.getCode())){
				if("TRADE_SUCCESS".equals(response.getTradeStatus())|| "TRADE_FINISHED".equals(response.getTradeStatus())){
					//成功
					queryPayStatusResponse.setPayStatus(true);
					queryPayStatusResponse.setRemoteTxJournalNo(response.getTradeNo());
					String orderAmt = response.getTotalAmount();
					queryPayStatusResponse.setOrderAmt(new BigDecimal(orderAmt));
				}else{
					if("WAIT_BUYER_PAY".equals(response.getTradeStatus())){
						queryPayStatusResponse.setPayStatusStr("USERPAYING");
					}else{
						queryPayStatusResponse.setPayStatus(false);
					}
				}
				queryPayStatusResponse.setSucess(true);
				queryPayStatusResponse.setCode(ResponseCode.OK.getCode());
				queryPayStatusResponse.setMsg(ResponseCode.OK.getMessage());
			} else {
				queryPayStatusResponse.setSucess(false);
				queryPayStatusResponse.setCode(ResponseCode.SEND_DATA_FAIL.getCode());
				queryPayStatusResponse.setMsg(ResponseCode.SEND_DATA_FAIL.getMessage());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return queryPayStatusResponse;
	}

}
